/**
 * Author Hung Tran
 */

package viettravel.DTO;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import viettravel.common.Constants;

import android.util.Log;

public class JSONParser {
	private InputStream mInputStream = null;
	private JSONObject mJSONObject = null;
	private String mJSONString = "";

	public JSONParser() {

	}

	public JSONObject getJSONFromUrl(String url) {
		try {
			HttpClient httpClient = createHttpClient();
			HttpGet httpGet = new HttpGet(url);

			HttpResponse httpResponse = httpClient.execute(httpGet);
			HttpEntity httpEntity = httpResponse.getEntity();
			mInputStream = httpEntity.getContent();

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					mInputStream, "UTF-8"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			mJSONString = sb.toString();
			Log.e("JSON Parser", mJSONString);
		} catch (Exception e) {
			Log.e("Buffer Error", "Error converting result " + e.toString());
		}

		// try parse the string to a JSON object
		try {
			mJSONObject = new JSONObject(mJSONString);
		} catch (JSONException e) {
			Log.e("JSON Parser", "Error parsing data " + e.toString());
		}

		// return JSON String
		return mJSONObject;
	}

	public JSONObject postJSON(String url, JSONObject json) {
		try {
			HttpClient httpclient = createHttpClient();
			HttpPost httpost = new HttpPost(url);
			StringEntity stringEntity = new StringEntity(json.toString(),
					"UTF-8");
			httpost.setEntity(stringEntity);
			httpost.setHeader("Accept", "application/json");
			httpost.setHeader("Content-type", "application/json");

			HttpResponse response = httpclient.execute(httpost);
			if (response.getStatusLine().getStatusCode() != 200) {
				return null;
			}
			HttpEntity httpEntity = response.getEntity();
			mInputStream = httpEntity.getContent();

		} catch (Exception e) {
			// TODO: handle exception
		}

		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					mInputStream, "UTF-8"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			mJSONString = sb.toString();
			Log.e("JSON Parser", mJSONString);
		} catch (Exception e) {
			Log.e("Buffer Error", "Error converting result " + e.toString());
		}

		// try parse the string to a JSON object
		try {
			mJSONObject = new JSONObject(mJSONString);
		} catch (JSONException e) {
			Log.e("JSON Parser", "Error parsing data " + e.toString());
		}

		// return JSON String
		return mJSONObject;

	}

	private static HttpClient createHttpClient() {
		HttpParams params = new BasicHttpParams();

		HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
		HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
		HttpProtocolParams.setUseExpectContinue(params, true);

		HttpConnectionParams.setConnectionTimeout(params,
				Constants.CONNECTION_TIMEOUT * 3);
		HttpConnectionParams.setSoTimeout(params, Constants.SOCKET_TIMEOUT * 3);

		SchemeRegistry schReg = new SchemeRegistry();
		schReg.register(new Scheme("http", PlainSocketFactory
				.getSocketFactory(), 80));
		schReg.register(new Scheme("https",
				SSLSocketFactory.getSocketFactory(), 443));
		ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
				params, schReg);

		return new DefaultHttpClient(conMgr, params);
	}

	public JSONObject makeCommentJson(int placeId, String cmtContent,
			String cmtSender, String cmtImage) {
		JSONObject jsonObject = new JSONObject();
		try {
			jsonObject.put(Constants.TAG_PLACES_ID, placeId);
			jsonObject.put(Constants.TAG_COMMENTS_TITLE, "Comment");
			jsonObject.put(Constants.TAG_COMMENTS_CONTENT, cmtContent);
			jsonObject.put(Constants.TAG_COMMENTS_SENDER, cmtSender);
			jsonObject.put(Constants.TAG_COMMENTS_IMAGE, cmtImage);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Log.d(Constants.TAG, jsonObject.toString());
		return jsonObject;

	}

	public JSONObject makeUserJson(String userId, String userName) {
		JSONObject jsonObject = new JSONObject();
		try {
			jsonObject.put(Constants.TAG_USERS_ID, userId);
			jsonObject.put(Constants.TAG_USERS_NAME, userName);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return jsonObject;
	}

	public JSONObject makeFavoriteJson(int placeId, String userId) {
		JSONObject jsonObject = new JSONObject();
		try {
			jsonObject.put(Constants.TAG_PLACES_ID, placeId);
			jsonObject.put(Constants.TAG_USERS_ID, userId);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return jsonObject;
	}

	public JSONObject makeJsonRate(int placeId, String userId, int score) {
		JSONObject jsonObject = new JSONObject();
		try {
			jsonObject.put(Constants.TAG_PLACES_ID, placeId);
			jsonObject.put(Constants.TAG_USERS_ID, userId);
			jsonObject.put(Constants.TAG_RATE_SCORE, score);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return jsonObject;
	}

	public JSONObject makeJsonPlace(String placeName, String description,
			Double placeLat, Double placeLong, int provinceId,
			List<Integer> activities, List<Integer> specialties,
			List<Integer> tours, List<String> images) {
		JSONObject jsonObject = new JSONObject();
		try {
			jsonObject.put(Constants.TAG_PLACES_NAME, placeName);
			jsonObject.put(Constants.TAG_PLACES_DESCIPTION, description);
			jsonObject.put(Constants.TAG_PLACES_LATITUDE, placeLat);
			jsonObject.put(Constants.TAG_PLACES_LONGTITUDE, placeLong);
			jsonObject.put(Constants.TAG_PROVINCE_ID, provinceId);
			JSONArray acivityArray = new JSONArray();
			for (Integer i : activities) {
				JSONObject json = new JSONObject();
				json.put(Constants.TAG_ACTIVITIES_ID, i);
				acivityArray.put(json);
			}
			jsonObject.put(Constants.TAG_ACTIVITIES, acivityArray);

			JSONArray specialtyArray = new JSONArray();
			for (Integer i : specialties) {
				JSONObject json = new JSONObject();
				json.put(Constants.TAG_SPECIALTIES_ID, i);
				specialtyArray.put(json);
			}
			jsonObject.put(Constants.TAG_SPECIALTIES, specialtyArray);

			JSONArray tourArray = new JSONArray();
			for (Integer i : tours) {
				JSONObject json = new JSONObject();
				json.put(Constants.TAG_TOURISTFORMS_ID, i);
				tourArray.put(json);
			}
			jsonObject.put(Constants.TAG_TOURISTFORMS, tourArray);

			JSONArray imageArray = new JSONArray();
			for (String i : images) {
				JSONObject json = new JSONObject();
				json.put(Constants.TAG_IMAGES_IMAGE, i);
				json.put(Constants.TAG_IMAGES_CAPTION, placeName + "image");
				imageArray.put(json);
				Log.d(Constants.TAG, i + " ");
			}
			jsonObject.put(Constants.TAG_IMAGES, imageArray);

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Log.d(Constants.TAG, jsonObject.toString());
		return jsonObject;
	}

	public static String getResponseFromUrl(URL url) {
		try {
			URLConnection urlConnection = url.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(
					urlConnection.getInputStream()));
			StringBuilder strBuilder = new StringBuilder();
			String temp;
			while ((temp = in.readLine()) != null) {
				strBuilder.append(temp);
			}
			return strBuilder.toString();
		} catch (IOException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return null;
	}

}